#include "web_handler.h"

#include <time.h>

void user_handler::web_handler::handle_event(
	boost::shared_ptr<network::message> n)
{
	if(n->type == network::RECEIVE) {
		boost::shared_ptr<model::dom> node(n->node);
		if(node->name() == "play") {
			do_play(node);
		} else if(node->name() == "list") {
			do_list(node);
		} else if(node->name() == "pause") {
			do_pause(node);
		} else if(node->name() == "list_temp") {
			do_temp(node);
		} else if(node->name() == "light") {
			do_light(node);
		} else if(node->name() == "tv") {
			do_tv(node);
		}
	} else if(n->type == network::DELETE) {
		boost::shared_ptr<user_handler::web_handler> tmp(_this.lock());
		fire_listener();
	}
}

void user_handler::web_handler::do_pause(boost::shared_ptr<model::dom> node)
{
	string clt = node->find_attrib("client");
	boost::shared_ptr<network::i_socket> sock(
		_music->get_socket(clt));
	sock->send(_mgr->get_sender(sock)->send(node));
}

void user_handler::web_handler::do_list(boost::shared_ptr<model::dom> node)
{
	// handle list-commands
	// optain lock
	_sock->send(_mgr->get_sender(_sock)->send(_music->list_clients()));
}

void user_handler::web_handler::do_play(boost::shared_ptr<model::dom> node)
{
	string clt = node->find_attrib("client");
	string file = node->find_attrib("file");
	string random = node->find_attrib("random");

	if(random == "random") {
		cout << "doing random..." << endl;
		do_random(clt, file);
		return;
	}
	
	boost::shared_ptr<network::i_socket> sock(
		_music->play_music(clt, file));
	sock->send(_mgr->get_sender(sock)->send(node));
}

void user_handler::web_handler::do_random(const string &client, 
					const string &file)
{
	string f = _music->suggest_title(client);

	boost::shared_ptr<model::dom> node(new model::dom("play"));
	node->insert_attrib("file", f);
	node->insert_attrib("client", client);
	boost::shared_ptr<network::i_socket> s(
		_music->play_music(client, f));

	// send to the client
	s->send(_mgr->get_sender(s)->send(node));
	// send to the web-interface
	_sock->send(_mgr->get_sender(_sock)->send(node));
}

void user_handler::web_handler::do_temp(boost::shared_ptr<model::dom> node)
{
	_controller->send(_mgr->get_sender(_controller)->send(node));
}

void user_handler::web_handler::do_light(boost::shared_ptr<model::dom> node)
{
	_controller->send(_mgr->get_sender(_controller)->send(node));
}

void user_handler::web_handler::do_tv(boost::shared_ptr<model::dom> node)
{
	_controller->send(_mgr->get_sender(_controller)->send(node));
}

